const single_bet = 50;
cc.Class({
    extends: cc.Component,

    properties: {
        iconPrefab: [cc.Prefab],
        winscoreLabel: cc.Label,
        coinNumLabel: cc.Label,
        music: [cc.AudioClip],
    },

    onLoad() {
        this.lobbyMain = cc.find("Canvas").getComponent("lobbyMain");
        this.lobbyNet = this.lobbyMain.lobbyNet;
        this.playerInfo = this.lobbyMain.playerInfo;
        this.mryNet = this.node.getComponent("mryNet");
        this.mryNet.init();
        this.reels = [];
        this.betLevel = 1;
        this.playAudio(0); //播放背景音乐

        this.winscore = 0;  // 赢分
        this.win = 0;  //去掉下注的净利润

        this.isFastMode = false; //快速模式
        this.jiangeTime = 0.2;  //每一行旋转间隔时间

        this.state = 0;  //游戏状态  0是正常状态  2是在旋转的状态  1是旋转结果返回
    },

    start() {
        this.bottom = this.node.getChildByName("bottom");
        this.bet_label = this.bottom.getChildByName("xiazhu").getChildByName("coin").getComponent(cc.Label); //下注
        let pIdLabel = this.bottom.getChildByName("id_bg").getChildByName("lael").getComponent(cc.Label); //玩家id
        this.coinNumLabel.string = this.playerInfo.playerCoin.toFixed(2);
        pIdLabel.string = "ID:" + this.playerInfo.playerId;
        for (let i = 0; i < this.reels.length; i++) {
            let reel = this.reels[i];
            reel.initReel();
        }

        this.bet_label.string = (this.betLevel * single_bet / this.lobbyMain.configJson.ratio).toFixed(2);

        this.node.getChildByName("game_version").getComponent(cc.Label).string = this.lobbyMain.configJson.version_mry;
    },

    onClick(event, target) {
        if (target != "spin" && target != "stop") {
            this.playAudio(3);
        }
        switch (target) {
            case "spin":  //旋转
                this.playAudio(1);
                this.click_spin();
                break;
            case "stop":  //停止
                this.stopReel();
                break;
            case "rule":  //规则
                this.showOrHideRule();
                break;
            case "fast":  //快速
                this.fastMode();
                break;
            case "menu":  //菜单
                this.openOrCloseMenu();
                break;
            case "sound":  //声音
                this.openOrCloseSound();
                break;
            case "home":  //返回
                this.backToLobby();
                break;
            case "bet_jia":  //加注
                this.bet_jia(1);
                break;
            case "bet_jian":  //减注
                this.bet_jia(0);
                break;


            default:

                break;
        }
    },


    //播放音频
    playAudio(id) {
        if (this.playerInfo.sound == "false") {
            return;
        }
        // 0 BGM  1 开始摇  2 转轮旋转完毕  3.按键音  4.赢钱音
        if (id == 0) {
            cc.audioEngine.playMusic(this.music[id], true);
        } else {
            cc.audioEngine.play(this.music[id], false, 1);
        }
    },

    //加注  
    bet_jia(parm) {
        if (parm == 1) {
            this.betLevel++;
        } else {
            this.betLevel--;
        }

        if (this.betLevel > 10) {
            this.betLevel = 1;
        }else if (this.betLevel < 1) {
            this.betLevel = 10;
        }
        this.bet_label.string = (this.betLevel * single_bet / this.lobbyMain.configJson.ratio).toFixed(2);
    },

    // 返回大厅
    backToLobby() {
        cc.audioEngine.pauseAll();
        this.mryNet.onDestroy();
        this.mryNet.isReContent = false;
        this.lobbyMain.getPlayerCoin();
        this.lobbyMain.playBgm()
        this.node.destroy();
    },

    //打开或者关闭声音
    openOrCloseSound() {
        let sound = this.playerInfo.sound;
        let menuNode = this.node.getChildByName("menu");
        let menu_panel = menuNode.getChildByName("menu_panel");
        if (sound == "true") {
            this.playerInfo.sound = "false";
            menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("on").active = false;
            menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("off").active = true;
            cc.audioEngine.stopAll();
        } else {
            this.playerInfo.sound = "true";
            menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("on").active = true;
            menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("off").active = false;
            this.playAudio(0);
        }
        this.playerInfo.writeToCache("sound", this.playerInfo.sound);
    },


    //打开或者关闭菜单
    openOrCloseMenu() {
        let menuNode = this.node.getChildByName("menu");
        let btn_menu = menuNode.getChildByName("btn_menu")
        let menu_panel = menuNode.getChildByName("menu_panel");

        if (menuNode.getChildByName("black").active) {
            menuNode.getChildByName("black").active = false;
            cc.tween(btn_menu)
                .to(0.3, { position: cc.v2(btn_menu.x - 140, btn_menu.y) })
                .start();
            cc.tween(menu_panel)
                .to(0.3, { position: cc.v2(menu_panel.x + 221, menu_panel.y) })
                .start();

        } else {
            menuNode.getChildByName("black").active = true;
            cc.tween(btn_menu)
                .to(0.3, { position: cc.v2(btn_menu.x + 140, btn_menu.y) })
                .start();
            cc.tween(menu_panel)
                .to(0.3, { position: cc.v2(menu_panel.x - 221, menu_panel.y) })
                .start();

            let sound = this.playerInfo.sound;
            if (sound == "true") {
                menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("on").active = true;
                menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("off").active = false;
            } else {
                menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("on").active = false;
                menu_panel.getChildByName("sound").getChildByName("switch").getChildByName("off").active = true;
            }
        }
    },


    // 快速模式
    fastMode() {
        if (this.state == 2) {
            return
        }
        let fastNode = this.bottom.getChildByName("fast").getChildByName("fast_1");
        fastNode.active = !fastNode.active;
        this.isFastMode = !this.isFastMode;

        for (let i = 0; i < this.reels.length; i++) {
            const reel = this.reels[i];
            if (this.isFastMode) {  //快速模式
                reel.symbolsNum = 10;
                reel.reelTime = 0.7;
                this.jiangeTime = 0;
            } else {
                reel.symbolsNum = 40;
                reel.reelTime = 2;
                this.jiangeTime = 0.2;
            }
            reel.initReel();
        }
    },

    // 显示或隐藏规则
    showOrHideRule() {
        let active = this.node.getChildByName("rule").active;
        this.node.getChildByName("rule").active = !active;
    },

    //点击旋转按钮
    click_spin() {
        if (this.state == 2) {
            return
        }
        this.state = 2;
        this.winscoreLabel.string = "0.00"
        let betCoin = parseFloat(this.bet_label.string);
        let pCoin = parseFloat(this.coinNumLabel.string);
        if (pCoin < betCoin) {
            let callback = () => {
                this.backToLobby();
                this.lobbyMain.openShopPanel();
                this.lobbyMain.closeTips();
            };
            this.lobbyMain.showTips("Not enough coins. Recharge now?", callback);
            this.state = 0;
            return;
        }
        this.unscheduleAllCallbacks();
        for (let i = 0; i < this.reels.length; i++) {
            const reel = this.reels[i];
            reel.state = 0;
        }
        this.startReel();
        let bet_now = this.betLevel * single_bet;
        this.mryNet.sendMessage({
            action: "spin",
            bet: bet_now,
            betLevel: this.betLevel,
            playerId: this.playerInfo.playerId,
        })

    },

    // 开始旋转
    startReel() {
        let index = 0;
        this.schedule(function () {
            if (index < this.reels.length) {
                const reel = this.reels[index];
                reel.startReel();
                index++;
            }
        }, this.jiangeTime, 5);
    },

    //旋转盘结果
    spinResponse(data) {
        this.winscore = data.winscore;
        this.win = data.win;
        this.winLineArr = data.winLineArr;
        this.newCoin = data.coin;

        let symbol = data.Symbol;
        let reelSymbols = [];
        for (let i = 0; i < 5; i++) {
            reelSymbols[i] = [];
        }
        for (let i = 0; i < symbol.length; i++) {
            reelSymbols[i % 5].push(symbol[i]);
        }
        for (let i = 0; i < this.reels.length; i++) {
            const reel = this.reels[i];
            reel.addResponse(reelSymbols[i]);
            reel.state = 1;
        }
        // this.startReel();
    },

    //旋转完成
    afterReel(reelId) {
        this.playAudio(2);
        if (reelId != 4) {
            return;
        }
        this.state = 0;
        console.log('旋转已完成');
        this.winscoreLabel.string = (this.winscore / this.playerInfo.ratio).toFixed(2);
        this.playerInfo.playerCoin += (this.win / this.playerInfo.ratio);

        this.showWinAnim();  //显示中奖动画
        this.setPlayerCoin(this.win); //设置金币显示
    },

    //设置金币显示
    setPlayerCoin(win) {
        let startValue = parseFloat(this.coinNumLabel.string);
        let endValue = startValue + win / this.playerInfo.ratio;

        let maxDuration = 1.0;
        let duration = Math.min(maxDuration, Math.max(0.2, win / 1000));

        let obj = { value: startValue };

        cc.tween(obj)
            .to(duration, { value: endValue }, {
                easing: 'quadOut',
                onUpdate: () => {
                    this.coinNumLabel.string = obj.value.toFixed(2);
                }
            })
            .start();
    },


    //显示中奖动画
    showWinAnim() {
        if (this.winLineArr.length == 0) {
            console.log("😭没中奖");
            return;
        }
        let winArr = this.winLineArr.flat();
        winArr = winArr.filter((item, index, self) => self.indexOf(item) === index);
        this.winLineArr.unshift(winArr);
        console.log(this.winLineArr);

        // let row = Math.floor((k - 1) / 5) + 1
        // let col = (k - 1) % 5 + 1

        let count = this.winLineArr.length; // 循环次数
        let times = 0;
        let self = this;
        this.schedule(() => {
            if (times == count) {
                times = 0;
            }
            let targetArr = self.winLineArr[times];  //取出对应的数组
            self.closeWinAnim();
            for (let i = 0; i < targetArr.length; i++) {
                const ele = targetArr[i];
                let row = Math.floor((ele - 1) / 5) + 1
                let col = (ele - 1) % 5
                let symbolPrefabs = self.reels[col].symbolPrefabs
                let Prewin = symbolPrefabs[symbolPrefabs.length - row].getChildByName("Prewin_line")
                if (Prewin) {
                    Prewin.getComponent(cc.Animation).play("win")
                }
            }
            times++;
        }, 3, count, 0.1);
    },

    closeWinAnim() {
        let self = this;
        for (let i = 0; i < 15; i++) {
            const ele = i + 1;
            let row = Math.floor((ele - 1) / 5) + 1
            let col = (ele - 1) % 5
            let symbolPrefabs = self.reels[col].symbolPrefabs
            let Prewin = symbolPrefabs[symbolPrefabs.length - row].getChildByName("Prewin_line")
            if (Prewin) {
                Prewin.getComponent(cc.Animation).stop()
            }
        }
    },


});
